#####
# Crossing borders: VOX data merging
#####

#####
# Load the vox data
vox <- haven::read_dta(here("data", "cleaning", "VOX", "vox_panel_1996_2016.dta")); setDT(vox)

# Convert the labelled classes to factors to ensure accuracy
for(j in colnames(vox)){
  if("haven_labelled" %in% class(vox[[j]])){
    set(vox, j = j, value = as.character(haven::as_factor(vox[[j]])))
  }
}

vox[ unique(cw[year %in% 2011:2012 , .(bfs, bfs19)]), on = c(munnr2012="bfs"), bfs19 := bfs19]

#####
# merge vox and 2019-vintage
vox <- merge(
  vox,
  cb,
  by = c("year", "bfs19"),
  all.x = T,
  all.y = F
)

#####
# recode variables for analysis

# Calm and order importance a91a
calmLUT <- c("wenig betont" = 1L, "2" = 2L, "3" = 3L, "4" = 4L, "5" = 5L, "stark betont" = 6L, "w.n. / k.A." = NA_integer_)
set(vox, NULL, "calmOrder", value = calmLUT[vox$a91a])


# environmental protection vs economic prosperity a91j
enviroLUT <- c("Umweltschutz" = 1L, "2" = 2L, "3" = 3L, "4" = 4L, "5" = 5L, "Wohlstand" = 6L, "w.n. / k.A." = NA_integer_)
set(vox, NULL, "enviroProtect", enviroLUT[vox$a91j])

# modern or traditional switzerland a91mg
tradLUT <- c("modern" = 1L, "2" = 2L, "3" = 3L, "4" = 4L, "5" = 5L, "Traditionen schützen" = 6L, "w.n. / k.A." = NA_integer_)
set(vox, NULL, "protectTrad", tradLUT[vox$a91mg])


# prepare the covariates for use in models

vox <- vox[, `:=`(
  income = fifelse(s41 == "unter Fr. 3000.-", 1,
                   fifelse(s41 == "zwischen Fr. 3000.- und 5000.-", 2,
                           fifelse(s41 == "zwischen Fr. 5000.- und 7000.-", 3,
                                   fifelse(s41 == "zwischen Fr. 7000.- und 9000.-", 4,
                                           fifelse(s41 == "über Fr. 9000.-", 5, NA_real_))))))]

vox2 <- vox[, `:=`(
  income = factor(income, levels = c(1, 2, 3, 4, 5)),
  female = fifelse(s11 == "männlich", 0,
                   fifelse(s11 == "weiblich", 1, NA_real_)),
  age = s12,
  education = factor(fifelse(education_highest == "primary education", "primary",
                                     fifelse(education_highest == "secondary education", "secondary",
                                             fifelse(education_highest == "tertiary education", "tertiary", NA_character_))),
                             levels = c("primary", "secondary", "tertiary")),
  employed = fifelse(s15 == "ja", 1,
                     fifelse(s15 == "nein", 0, NA_real_)),
  married = fifelse(s18 == "verheiratet", 1,
                    fifelse(s18 == "ledig" | s18 == "verwitwet" | s18 == "geschieden" | s18 == "lebt mit Partner", 0, NA_real_))
)]


# Assuming the previous transformations are already done
vox <- vox[, .(income, female, age, education, employed, married, protectTrad, voxnr, enviroProtect, calmOrder,
               BR, travelMUNmin, border15, border30, gewteil, transBorder15, freeBorder15, bfs19, year)]


# save the output for easy access during modelling
qsave(vox, here("data", "vox.qs"))









